<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <link rel="stylesheet" href="./css/adminUserList.css">
    <script src="./js/jquery.min.js"></script>
</head>
<body>
<div class="main-wrapper">
    <div class="sidebar">
        <h3>医院病例管理系统</h3>
        <ul>
            <li><a href="./adminUserList.html" class="active">用户管理</a></li>
            <li><a href="./adminMedicalRecordList.html">病历管理</a></li>
            <li><a href="./adminPersonalCenter.html">个人信息管理</a></li>
            <li><a href="./adminMedicalTemplate.html">病历模板管理</a></li>
            <li><a href="./adminUpdateRequest.html">信息修改申请</a></li>
        </ul>
    </div>
    <div class="main-content">
        <div class="info-card">
            <h2>用户列表</h2>
            <div class="search-input-container">
                <input type="text" id="userSearchInput" class="search-input" placeholder="输入用户名或昵称搜索">
            </div>
            <div class="button-container">
                <button type="button" class="btn btn-success" id="addUserButton">添加用户</button>
            </div>
            <table class="user-table">
                <thead>
                <tr>
                    <th>头像</th>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>昵称</th>
                    <th>角色</th>
                    <th>性别</th>
                    <th>年龄</th>
                    <th>邮箱</th>
                    <th>手机</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="userTableBody">
                <!-- 用户数据将在这里加载 -->
                </tbody>
            </table>
            <div id="loading" class="loading-message">加载中...</div>
            <div id="error" class="error-message" style="display: none;">加载失败</div>
        </div>
    </div>
</div>

<!-- 编辑用户模态框 -->
<div id="editUserModal" class="modal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑用户信息</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="editUserModalForm">
                    <input type="hidden" id="modalUserId">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="modalAvatar">头像</label>
                            <div>
                                <div id="modalAvatarPreview" class="avatar-preview" style="display: none;">
                                    <img src="" alt="Avatar">
                                </div>
                                <div id="modalAvatarUpload" class="avatar-upload-area">
                                    +
                                </div>
                                <small class="form-text">点击上传头像</small>
                            </div>
                        </div>
                        <div class="form-group">
                            <input type="hidden" id="modalAvatarPath">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="modalUsername">账号</label>
                            <input type="text" class="form-control" id="modalUsername" readonly>
                        </div>
                        <div class="form-group">
                            <label for="modalUserRole">角色</label>
                            <select class="form-control" id="modalUserRole">
                                <option value="0">患者</option>
                                <option value="1">管理员</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="modalNickname">昵称</label>
                            <input type="text" class="form-control" id="modalNickname">
                        </div>
                        <div class="form-group">
                            <label for="modalGender">性别</label>
                            <select class="form-control" id="modalGender">
                                <option value="0">男</option>
                                <option value="1">女</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="modalAge">年龄</label>
                            <input type="text" class="form-control" id="modalAge">
                        </div>
                        <div class="form-group">
                            <label for="modalPhone">手机号码</label>
                            <input type="text" class="form-control" id="modalPhone">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="modalEmail">邮箱</label>
                            <input type="text" class="form-control" id="modalEmail">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="saveUserModalButton">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 添加用户模态框 -->
<div id="addUserModal" class="modal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加新用户</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="addUserModalForm">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="addAvatar">头像</label>
                            <div>
                                <div id="addAvatarPreview" class="avatar-preview" style="display: none;">
                                    <img src="" alt="Avatar">
                                </div>
                                <div id="addAvatarUpload" class="avatar-upload-area">
                                    +
                                </div>
                                <small class="form-text">点击上传头像</small>
                            </div>
                        </div>
                        <div class="form-group">
                            <input type="hidden" id="addAvatarPath">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="addUsername">账号</label>
                            <input type="text" class="form-control" id="addUsername" required>
                        </div>
                        <div class="form-group">
                            <label for="addNickname">昵称</label>
                            <input type="text" class="form-control" id="addNickname" required>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="addPassword">密码</label>
                            <input type="password" class="form-control" id="addPassword" required>
                        </div>
                        <div class="form-group">
                            <label for="addCheckPassword">确认密码</label>
                            <input type="password" class="form-control" id="addCheckPassword" required>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="addUserRole">角色</label>
                            <select class="form-control" id="addUserRole" required>
                                <option value="0">患者</option>
                                <option value="1">管理员</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="addGender">性别</label>
                            <select class="form-control" id="addGender">
                                <option value="0">男</option>
                                <option value="1">女</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="addAge">年龄</label>
                            <input type="text" class="form-control" id="addAge">
                        </div>
                        <div class="form-group">
                            <label for="addPhone">手机号码</label>
                            <input type="text" class="form-control" id="addPhone">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group-full">
                            <label for="addEmail">邮箱</label>
                            <input type="text" class="form-control" id="addEmail">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group-full">
                            <label for="addHistory">既往史</label>
                            <textarea class="form-control" id="addHistory" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group-full">
                            <label for="addAllergy">过敏史</label>
                            <textarea class="form-control" id="addAllergy" rows="3"></textarea>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveAddUserButton">保存</button>
            </div>
        </div>
    </div>
</div>

<script>
$(function(){
    const backendBaseUrl = 'http://localhost:8080';

    // 获取用户列表数据
    function loadUsers() {
        $('#loading').show();
        $('#error').hide();
        const searchTerm = $('#userSearchInput').val();

        $.ajax({
            url: backendBaseUrl + '/admin/users/list',
            type: 'GET',
            xhrFields: { withCredentials: true },
            success: function(res){
                $('#loading').hide();
                if(res.code === 0 && res.data){
                    let users = res.data;
                    const $tbody = $('#userTableBody');
                    $tbody.empty();

                    if (searchTerm) {
                        const lowerSearchTerm = searchTerm.toLowerCase();
                        users = users.filter(user =>
                            (user.username && user.username.toLowerCase().includes(lowerSearchTerm)) ||
                            (user.nickname && user.nickname.toLowerCase().includes(lowerSearchTerm))
                        );
                    }

                    if (users.length === 0) {
                        $tbody.append('<tr><td colspan="11" class="text-center">无匹配用户</td></tr>');
                        return;
                    }

                    users.forEach(user => {
                        const role = user.role === 1 ? '管理员' : '患者';
                        const genderDisplay = user.gender === 0 ? '男' : '女';

                        const $row = $('<tr>');
                        const $avatarCell = $('<td>');
                        if (user.avatar) {
                            const $avatarImg = $('<img>')
                                .attr('src', user.avatar)
                                .attr('alt', '头像')
                                .addClass('user-avatar');
                            $avatarCell.append($avatarImg);
                        } else {
                            $avatarCell.text('无头像');
                        }
                        $row.append($avatarCell);

                        $row.append($('<td>').text(user.id));
                        $row.append($('<td>').text(user.username));
                        $row.append($('<td>').text(user.nickname || '-'));
                        $row.append($('<td>').text(role));
                        $row.append($('<td>').text(genderDisplay));
                        $row.append($('<td>').text(user.age || '-'));
                        $row.append($('<td>').text(user.email || '-'));
                        $row.append($('<td>').text(user.phone || '-'));
                        $row.append($('<td>').text(new Date(user.createTime).toLocaleString()));

                        const $editButton = $('<button>')
                            .addClass('btn btn-primary edit-btn')
                            .text('编辑')
                            .attr('data-id', user.id);
                        const $deleteButton = $('<button>')
                            .addClass('btn btn-danger delete-btn')
                            .text('删除')
                            .attr('data-id', user.id);

                        const $actionsCell = $('<td>').append($editButton).append($deleteButton);
                        $row.append($actionsCell);

                        $tbody.append($row);
                    });

                } else {
                    $('#error').text(res.message || '获取用户列表失败').show();
                }
            },
            error: function(){
                $('#loading').hide();
                $('#error').text('请求失败，请稍后重试').show();
            }
        });
    }

    // 删除用户
    function deleteUser(userId) {
        if (confirm('确定要删除此用户吗？')) {
            $.ajax({
                url: backendBaseUrl + '/admin/users/delete/' + userId,
                type: 'POST',
                xhrFields: { withCredentials: true },
                success: function(res){
                    if(res.code === 0){
                        alert('用户删除成功');
                        loadUsers();
                    } else {
                        alert(res.message || '删除失败');
                    }
                },
                error: function(){
                    alert('删除失败，请稍后重试');
                }
            });
        }
    }

    // 加载用户数据并显示编辑模态框
    function loadUserDataAndShowModal(userId) {
        $('#modalUserId').val(userId);
        $('#editUserModalForm')[0].reset();
        $('#modalAvatarPreview').hide();
        $('#modalAvatarUpload').show();
        $('#modalAvatarUpload').next('small').show();
        $('#modalAvatarPath').val('');
        
        $.ajax({
            url: backendBaseUrl + '/admin/users/' + userId,
            type: 'GET',
            xhrFields: { withCredentials: true },
            success: function(res) {
                if (res.code === 0 && res.data) {
                    const user = res.data;
                    $('#modalUsername').val(user.username);
                    $('#modalUserRole').val(user.role);
                    $('#modalNickname').val(user.nickname || '');
                    $('#modalGender').val(user.gender);
                    $('#modalAge').val(user.age || '');
                    $('#modalPhone').val(user.phone || '');
                    $('#modalEmail').val(user.email || '');
                    $('#modalAvatarPath').val(user.avatar || '');

                    if (user.avatar) {
                        $('#modalAvatarPreview img').attr('src', user.avatar);
                        $('#modalAvatarPreview').show();
                        $('#modalAvatarUpload').hide();
                        $('#modalAvatarUpload').next('small').hide();
                    }

                    showModal('editUserModal');
                } else {
                    alert('获取用户信息失败: ' + (res.message || ''));
                }
            },
            error: function() {
                alert('获取用户信息失败，请稍后重试。');
            }
        });
    }

    // 显示模态框
    function showModal(modalId) {
        const $modal = $('#' + modalId);
        $modal.css('display', 'block').addClass('show');
        
        // 点击背景关闭模态框
        $modal.on('click', function(e) {
            if ($(e.target).hasClass('modal')) {
                hideModal(modalId);
            }
        });
        
        // 关闭按钮事件
        $modal.find('.close, .btn-secondary').on('click', function() {
            hideModal(modalId);
        });
    }

    // 隐藏模态框
    function hideModal(modalId) {
        const $modal = $('#' + modalId);
        $modal.css('display', 'none').removeClass('show');
        $modal.off('click');
        $modal.find('.close, .btn-secondary').off('click');
    }

    // 模态框保存按钮点击事件
    $('#saveUserModalButton').click(function(){
        const userId = $('#modalUserId').val();
        const userData = {
            id: userId,
            nickname: $('#modalNickname').val(),
            phone: $('#modalPhone').val(),
            email: $('#modalEmail').val(),
            age: $('#modalAge').val(),
            gender: $('#modalGender').val(),
            role: $('#modalUserRole').val(),
            avatar: $('#modalAvatarPath').val()
        };

        $.ajax({
            url: backendBaseUrl + '/admin/users/update',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(userData),
            xhrFields: { withCredentials: true },
            success: function(res) {
                if (res.code === 0) {
                    alert('用户信息更新成功');
                    hideModal('editUserModal');
                    loadUsers();
                } else {
                    alert('用户信息更新失败: ' + (res.message || ''));
                }
            },
            error: function() {
                alert('用户信息更新失败，请稍后重试。');
            }
        });
    });

    // 头像上传相关
    $('#editUserModalForm .form-group').has('label[for="modalAvatar"]').append(
        '<input type="file" id="modalAvatarFileInput" accept="image/*" style="display: none;">'
    );

    $('#modalAvatarFileInput').on('change', function(e) {
        var file = e.target.files[0];
        if (file) {
            var formData = new FormData();
            formData.append('file', file);

            $.ajax({
                url: backendBaseUrl + '/user/upload/avatar',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                xhrFields: { withCredentials: true },
                success: function(res) {
                    if(res.code === 0) {
                        $('#modalAvatarPreview img').attr('src', res.data);
                        $('#modalAvatarPreview').show();
                        $('#modalAvatarPath').val(res.data);
                        $('#modalAvatarUpload').hide();
                        $('#modalAvatarUpload').next('small').hide();
                    } else {
                        alert(res.message || '头像上传失败');
                    }
                },
                error: function() {
                    alert('头像上传失败，请稍后重试');
                }
            });
        }
    });

    $('#modalAvatarUpload, #modalAvatarPreview').click(function() {
        $('#modalAvatarFileInput').click();
    });

    // 事件委托绑定
    $('#userTableBody').on('click', '.delete-btn', function(){
        const userId = $(this).data('id');
        deleteUser(userId);
    });

    $('#userTableBody').on('click', '.edit-btn', function(){
        const userId = $(this).data('id');
        if (userId) {
            loadUserDataAndShowModal(userId);
        } else {
            alert('无法获取用户ID，请稍后重试。');
        }
    });

    // 搜索功能
    $('#userSearchInput').on('input', loadUsers);

    // 添加用户按钮点击事件
    $('#addUserButton').click(function(){
        // 清空表单
        $('#addUserModalForm')[0].reset();
        // 显示添加用户模态框
        showModal('addUserModal');
    });

    // 添加用户模态框头像上传相关
    $('#addUserModalForm .form-group').has('label[for="addAvatar"]').append(
        '<input type="file" id="addAvatarFileInput" accept="image/*" style="display: none;">'
    );
    $('#addAvatarFileInput').on('change', function(e) {
        var file = e.target.files[0];
        if (file) {
            var formData = new FormData();
            formData.append('file', file);
            $.ajax({
                url: backendBaseUrl + '/user/upload/avatar',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                xhrFields: { withCredentials: true },
                success: function(res) {
                    if(res.code === 0) {
                        $('#addAvatarPreview img').attr('src', res.data);
                        $('#addAvatarPreview').show();
                        $('#addAvatarPath').val(res.data);
                        $('#addAvatarUpload').hide();
                        $('#addAvatarUpload').next('small').hide();
                    } else {
                        alert(res.message || '头像上传失败');
                    }
                },
                error: function() {
                    alert('头像上传失败，请稍后重试');
                }
            });
        }
    });
    $('#addAvatarUpload, #addAvatarPreview').click(function() {
        $('#addAvatarFileInput').click();
    });

    // 保存添加用户按钮点击事件
    $('#saveAddUserButton').off('click').on('click', function(){
        const userData = {
            username: $('#addUsername').val(),
            password: $('#addPassword').val(),
            checkPassword: $('#addCheckPassword').val(),
            nickname: $('#addNickname').val(),
            role: parseInt($('#addUserRole').val()),
            gender: parseInt($('#addGender').val()),
            age: $('#addAge').val() ? parseInt($('#addAge').val()) : null,
            phone: $('#addPhone').val(),
            email: $('#addEmail').val(),
            history: $('#addHistory').val(),
            allergy: $('#addAllergy').val(),
            avatar: $('#addAvatarPath').val()
        };

        // 简单的客户端验证
        if (!userData.username || !userData.password || !userData.checkPassword || !userData.nickname || userData.role === null || userData.gender === null) {
            alert('请填写所有必填项 (账号, 密码, 确认密码, 昵称, 角色, 性别)');
            return;
        }

        if (userData.password !== userData.checkPassword) {
            alert('密码和确认密码不匹配');
            return;
        }

        $.ajax({
            url: backendBaseUrl + '/admin/users/add', // 修改为新的管理员添加用户接口
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(userData),
            xhrFields: { withCredentials: true },
            success: function(res) {
                if (res.code === 0) {
                    alert('用户添加成功');
                    hideModal('addUserModal');
                    loadUsers(); // 刷新用户列表
                } else {
                    alert('用户添加失败: ' + (res.message || ''));
                }
            },
            error: function() {
                alert('用户添加失败，请稍后重试');
            }
        });
    });

    // 初始加载
    loadUsers();
});
</script>
</body>
</html> 